package common;

/**
 * @author fance
 * @date 18-4-19 下午1:20
 */
public final class Util {


    public static void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
    public static void reverse(char[] A, int lo, int hi) {
        while (lo < hi) {
            char tmp = A[lo];
            A[lo] = A[hi];
            A[hi] = tmp;
            lo++;
            hi--;
        }
    }
    public static int binarySerach(int[] nums, int target) {
        if (nums == null || nums.length < 1) {
            return -1;
        }
        int lo = 0;
        int hi = nums.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target){
                hi = mid - 1;
            } else {
                lo = mid + 1;
            }
        }
        return -1;
    }

    public static int getListLen(ListNode head) {
        ListNode tmp = head;
        int cnt = 0;
        while (tmp != null) {
            cnt++;
            tmp = tmp.next;
        }
        return cnt;
    }

    public static void printList(ListNode head) {
        ListNode tmp = head;
        while (tmp != null) {
            System.out.print(tmp.val + " ");
            tmp = tmp.next;
        }
        System.out.println();
    }

    public static boolean isPalindrome(String s) {
        int st = 0,end = s.length() - 1;
        while (st < end) {
            if (s.charAt(st++) != s.charAt(end--)) {
                return false;
            }
        }
        return true;
    }
    public static boolean isPalindrome(String s, int lo, int hi) {
        while (lo < hi) {
            if (s.charAt(lo++) != s.charAt(hi--)) {
                return false;
            }
        }
        return true;
    }
    public static boolean isUniqueStr(String s) {
        boolean[]  map = new boolean[256];
        for (int i = 0; i < s.length(); i++) {
            if (map[s.charAt(i)]) {
                return false;
            }
            map[s.charAt(i)] = true;
        }
        return true;
    }
    public static int sum(int[] nums, int lo,int hi) {
        int sum = 0;
        for (int i = lo; i <= hi; i++) {
            sum += nums[i];
        }
        return sum;
    }
}
